<template>
  <div class="app-container">
    <div class="app-wrap" style="height:100%;overflow:auto;">
      <div class="flexAround ">
        <div class="infoBox width25">
          <p>当前在线人数</p>
          <span><span class="numberText">{{ nowNumber }}</span>人</span>
        </div>
        <div class="infoBox width25">
          <p>同时在线峰值人数</p>
          <span><span class="numberText">{{ max }}</span>人</span>
        </div>
        <div class="infoBox width25">
          <p>日均活跃人数(月)</p>
          <span><span class="numberText">{{ activeNumber }}</span>人</span>
        </div>
      </div>
      <!-- 同时在线 -->
      <div class="border-line">
        <el-button type="success" size="medium" icon="el-icon-refresh" class="marginL10" @click="refresh">更新实时数据</el-button>
        <!-- <div class="number-person marginB20">
        <span class="marginR20" v-for="(item,index) in timeDayDataList" :key="index">
          <span class="colorGre">{{ item.name }}</span> : 【 <span class="colorRed">{{ item.number }}</span> 】人
        </span>
      </div> -->
        <p>同时在线人数统计</p>
        <div class="flexStart">
          <el-form class="flex" ref="activeFrom" :model="listQueryThree" :rules="{}" label-position="right" label-width="70px">
            <el-form-item label="渠道：">
              <el-select v-model="listQueryThree.agent_id" placeholder="请选择渠道：" filterable style="width:240px">
                <el-option label="全部" value="" ></el-option>
                <el-option :label="second.label" :value="second.value" v-for="(second, two) in channelData" :key="two"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期时间:" label-width="80px">
              <el-date-picker is-range v-model="listQueryThree.dateTime" type="date" class="full-width-input time-box" :clearable="false" />
            </el-form-item>
            <el-button class="marginB20 marginL20" size="medium" type="primary" @click="timeDayOperation">查 询</el-button>
            <el-button class="marginB20 marginL20" size="medium" type="info" @click="timeDayOperation">刷 新</el-button>
          </el-form>
        </div>
        <div id="echartThree" class="echarts"></div>
      </div>

      <!-- 日均在线 -->
      <div class="border-line">
        <!-- <div class="number-person marginB20">
        <span class="marginR20" v-for="(item,index) in activeDayDataList" :key="index">
          <span class="colorGre">{{ item.name }}</span> : 【 <span class="colorRed">{{ item.number }}</span> 】人
        </span>
      </div> -->
        <p>日均在线人数统计</p>
        <div class="flexStart">
          <el-form class="flex" ref="activeFrom" :model="listQueryTwo" :rules="{}" label-position="right" label-width="70px">
            <el-form-item label="渠道：">
              <el-select v-model="listQueryTwo.agent_id" placeholder="请选择渠道：" filterable style="width:240px">
                <el-option label="全部" value="" ></el-option>
                <el-option :label="second.label" :value="second.value" v-for="(second, two) in channelData" :key="two"></el-option>
              </el-select>
            </el-form-item>
            <ChannelDate v-model="listQueryTwo.dateTime" type="monthrange"/>
            <!-- <el-form-item label="日期时间:" label-width="80px">
              <el-date-picker is-range v-model="listQueryTwo.dateTime" type="month" class="full-width-input time-box" :clearable="false" />
            </el-form-item> -->
            <el-button class="marginB20 marginL20" size="medium" type="primary" @click="onlineDayOperation">查 询</el-button>
            <el-button class="marginB20 marginL20" size="medium" type="info" @click="onlineDayOperation">刷 新</el-button>
          </el-form>
        </div>
        <div id="echartTwo" class="echarts"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  dayPlayerActive,
  timePlayerActive,
  getPersonLine
} from "@/api/statistics";
import {
  throttle
} from '@/utils/index'
import ChannelDate from '@/components/ChannelDate.vue'
export default {
  name: "online",
  components: {
    ChannelDate
  },
  data () {
    return {
      channelData: this.$store.state.commonState.channelDataArray,
      listQueryTwo: {
        type: 1,
        agent_id: '',
        dateTime: [this.$public.getDateMonth('s', 0),this.$public.getDateMonth('e', 0)],
        start_time: '',
        end_time: '',
      },
      listQueryThree: {
        type: 1,
        agent_id: '',
        dateTime: this.$public.getDateDay(0),
        start_time: '',
        end_time: '',
      },
      keyDataOne: [],
      legendDataOne: [],
      keyDataTwo: [],
      legendDataTwo: [],
      keyDataThree: [],
      legendDataThree: [],
      activeDayDataList: [],// 日均在线
      timeDayDataList: [],// 同时在线
      myChartOne: null,
      myChartTwo: null,
      myChartThree: null,
      activeNumber: 0,// 日均在线
      timeNumber: [],// 同时在线(峰值)
      nowNumber: 0,// 实时在线
    };
  },
  computed: {
    max () {
      if (this.timeNumber.length != 0) {
        return Math.max.apply(null, this.timeNumber)
      } else {
        return 0
      }
    }
  },
  created () {
    // this.nowDayOperation()
    // this.timeDayOperation()
    // this.onlineDayOperation()
  },
  activated(){
    this.channelData=this.$store.state.commonState.channelDataArray
    this.nowDayOperation()
    this.timeDayOperation()
    this.onlineDayOperation()
  },
  methods: {
    // 实时在线
    nowDayOperation (status) {
      let that = this, params = {};
      params.start_time = that.$public.getDateDay(0) + ' 00:00:00'
      params.end_time = that.$public.standardDate(new Date())
      timePlayerActive(params).then(function (res) {
        if (res.code == 1) {
          if (res.data[0]) {
            that.nowNumber = res.data[0].count
            if(status){
              that.$message.success('数据已更新')
            }
          }
        }
      })
    },
    // 同时在线
    async timeDayOperation (status) {
      let that = this, agentData = [],params = JSON.parse(JSON.stringify(that.listQueryThree));
      that.listLoading = true;
      that.keyDataThree = []
      that.legendDataThree = []
      that.timeDayDataList = []
      if (params.dateTime) {
        params.start_time = that.$public.standardDate(params.dateTime).substr(0, 10) + ' 00:00:00'
        params.end_time = that.$public.standardDate(params.dateTime).substr(0, 10) + ' 23:59:59'
      } else {
        params.start_time = ''
        params.end_time = ''
      }
      const response= await getPersonLine(params)
      if (response.code == 1) {
        if (response.data) {
          response.data.map(item => {
            item.date=item.date.substring(11,21)
            agentData.push(item.agent_id)
            that.keyDataThree.push(item.date)
            that.legendDataThree.push(that.$public.channelLabel(item.agent_id))
          })
          agentData = Array.from(new Set(agentData));
          that.keyDataThree = Array.from(new Set(that.keyDataThree));
          that.legendDataThree = Array.from(new Set(that.legendDataThree));
          that.timeDayDataList=that.playerOnlineData(agentData,that.keyDataThree,response.data)
          that.timeNumber=that.playerOnlineData(agentData,that.keyDataThree,response.data,'number')
          if(status){
            that.$message.success('数据已更新')
          }
        }
        that.operationEchartsThree()
      }else{
        that.$message.error(response.msg)
      }
    },
    // 同时在线-折线图
    operationEchartsThree () {
      let that = this;
      if (!that.myChartThree) {
        var chartDom = document.getElementById('echartThree');
        that.myChartThree = echarts.init(chartDom);
      } else {
        that.myChartThree.clear()
      }
      var option;
      option = {
        legend: {
          type: 'scroll',
          data: that.legendDataThree,
        },
        tooltip: {
          trigger: 'item',
          triggerOn : 'mousemove',
          axisPointer: {     // 坐标轴指示器，坐标轴触发有效
            type: 'line',   // 默认为直线，可选为：'line' | 'shadow' 'cross'
            label:{}
          },
          formatter:function (params) {
            return '<div>'+params.seriesName+ '在线<span style="color: red;">'+params.value+'</span>人</div>';
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          splitLine: { show: false },
          axisPointer: {
            type: 'shadow'
          },
          data: that.keyDataThree
        },
        yAxis: {
          type: 'value',
        },
        series: that.timeDayDataList
      };
      option && that.myChartThree.setOption(option);
    },
    // 日均活跃
    async onlineDayOperation (status) {
      let that = this, agentData = [], number = [], params = JSON.parse(JSON.stringify(that.listQueryTwo));
      that.listLoading = true;
      that.keyDataTwo = []
      that.legendDataTwo = []
      that.activeDayDataList = []
      if (params.dateTime && params.dateTime[0]) {
        params.start_time = that.$public.standardDate(params.dateTime[0]).substr(0, 10) + ' 00:00:00'
        params.end_time = that.$public.standardDate(params.dateTime[1]).substr(0, 10) + ' 23:59:59'
      } else {
        params.start_time = ''
        params.end_time = ''
      }
      const response= await  dayPlayerActive(params)
      if (response.code == 1) {
        if (response.data) {
          response.data.map(item => {
            item.show_time=item.show_time.substring(0,11)
            agentData.push(item.agent_id)
            that.keyDataTwo.push(item.show_time)
            that.legendDataTwo.push(that.$public.channelLabel(item.agent_id))
            number.push(item.active_person_num)
          })
          agentData = Array.from(new Set(agentData));
          that.legendDataTwo = Array.from(new Set(that.legendDataTwo));
          that.keyDataTwo = Array.from(new Set(that.keyDataTwo));
          that.activeDayDataList=that.playerActiveData(agentData,that.keyDataTwo,response.data)
          that.activeNumber=parseInt(number.reduce((acc, curr) => acc + curr, 0)/30)
          if(status){
            that.$message.success('数据已更新')
          }
          that.operationEchartsTwo()
        }
      }else{
        that.$message.error(response.msg)
      }
    },
    // 日均在线-折线图
    operationEchartsTwo () {
      let that = this;
      if (!that.myChartTwo) {
        var chartDom = document.getElementById('echartTwo');
        that.myChartTwo = echarts.init(chartDom);
      } else {
        that.myChartTwo.clear()
      }
      var option;
      option = {
        legend: {
          type: 'scroll',
          data: that.legendDataTwo,
        },
        tooltip: {
          trigger: 'item',
          triggerOn : 'mousemove',
          axisPointer: {     // 坐标轴指示器，坐标轴触发有效
            type: 'line',   // 默认为直线，可选为：'line' | 'shadow' 'cross'
            label:{}
          },
          formatter:function (params) {
            return '<div>'+params.seriesName+ '在线<span style="color: red;">'+params.value+'</span>人</div>';
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          splitLine: { show: false },
          axisPointer: {
            type: 'shadow'
          },
          data: that.keyDataTwo
        },
        yAxis: {
          type: 'value',
        },
        series: that.activeDayDataList
      };
      option && that.myChartTwo.setOption(option);
    },
    playerOnlineData(agentData,keyData,data,type){
      let arrayData=[],arrData=[],number=[];
      agentData.map(id=>{
        keyData.map(date=>{
          arrayData.push({agent_id:id,date:date,user_line_num:0})
        })
      })
      arrayData.map(allItem=>{
        data.map(item=>{
          if(allItem.agent_id==item.agent_id && allItem.date==item.date){
            allItem.user_line_num=item.user_line_num
          }
        })
      })
      agentData.map(id => {
        let data = [];
        arrayData.map(item => {
          if (id == item.agent_id) {
            data.push(item.user_line_num)
            number.push(item.user_line_num)
          }
        })
        arrData.push({ name: this.$public.channelLabel(id), data: data, type: 'line', showAllSymbol: true, number: data.reduce((acc, curr) => acc + curr, 0) })
      })
      if(type){
        return number
      }else{
        return arrData
      }
    },
    playerActiveData(agentData,keyData,data){
      let arrayData=[],arrData=[];
      agentData.map(id=>{
        keyData.map(date=>{
          arrayData.push({agent_id:id,show_time:date,active_person_num:0})
        })
      })
      arrayData.map(allItem=>{
        data.map(item=>{
          if(allItem.agent_id==item.agent_id && allItem.show_time==item.show_time){
            allItem.active_person_num=item.active_person_num
          }
        })
      })
      agentData.map(id => {
        let data = [];
        arrayData.map(item => {
          if (id == item.agent_id) {
            data.push(item.active_person_num)
          }
        })
        arrData.push({ name: this.$public.channelLabel(id), data: data, type: 'line', showAllSymbol: true, number: data.reduce((acc, curr) => acc + curr, 0) })
      })
      return arrData
    },
    // 刷新
    refresh: throttle(function () {
      this.nowDayOperation('success')
      this.timeDayOperation('success')
      this.onlineDayOperation('success')
    }, 2000),
  },
};
</script>

<style lang="scss" scoped>
.border-line {
  width: 100%;
  padding: 20px;
  margin: 20px auto;
  background: #f9f9f9;
  border-radius: 5px;
  p {
    font-size: 24px;
  }
  .number-person {
    font-size: 20px;
    font-weight: 600;
  }
  .echarts {
    width: 100%;
    height: 400px;
    background-color: #ffffff;
  }
  .refresh {
    font-size: 30px;
    font-weight: 600;
    margin-top: 5px;
  }
  .refresh :hover {
    cursor: pointer;
    color: green;
    transition: all 0.3s ease-out;
    transform: scale(1.2);
  }
  .width25 {
    margin: 5px;
    border: 1px solid #999999;
    border-radius: 5px;
    text-align: center;
  }
}
.infoBox {
  cursor: pointer;
  color: #fff;
  font-size: 18px;
  padding: 20px 30px 40px 100px;
  font-weight: 550;
  border-radius: 15px;
  background-color: cornflowerblue;
  .numberText {
    font-size: 24px;
    border-bottom: 1px solid #fff;
  }
  &:hover {
    transition: all 0.3s ease-out;
    transform: scale(1.1);
  }
}
.infoBox:nth-of-type(1) {
  background: url('../../../assets/img/1.png') no-repeat;
  background-size: 100% 100%;
}
.infoBox:nth-of-type(2) {
  background: url('../../../assets/img/3.png') no-repeat;
  background-size: 100% 100%;
}
.infoBox:nth-of-type(3) {
  background: url('../../../assets/img/6.png') no-repeat;
  background-size: 100% 100%;
}
</style>
